<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/5/7
 * Time: 10:55
 * 好友列表
 */
namespace app\api\controller;
use think\Db;
class Friend extends Base {

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {

        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    //统计好友的数量
    public function countNum(){
        extract(input());
        $where['friend_status'] = 2;
        $where['friend_user_id'] = $user_id;
        $list = Db::table('up_friend')->where($where)->count();
        return  json(array('status'=>200,'msg'=>$list));
    }

    /**
     * other_id
     * 添加好友之前看这个人的简要信息
     * 直接调用 My/userBaseInfo，传 other_id
     * @return \think\response\Json
     */

    /**
     * other_id $friend_verify
     * 添加好友
     * @return \think\response\Json
     */
    public function addFriend(){
        $user_id = input('param.user_id');
        $friend_verify = input('param.friend_verify');
        $friend_from = input('friend_from');
        $groupid = $this->createGroupBefore($user_id);
        if($groupid != false){
            $userId = input('param.other_id');
            $where['friend_user_id'] = $user_id;//自己
            $where['friend_other_user'] = $userId;//添加的人
            if($user_id == $userId){
                return  json(array('status'=>100,'msg'=>"不能自己添加自己为好友"));
            }
            $info = Db::table('up_friend')->where($where)->find();
            if($info){
                if($info['friend_status'] == 2){
                    return  json(array('status'=>100,'msg'=>"你们已经是好友了"));
                }else{
                    //有可能申请过了，此时主要为了更新时间
                    $res = Db::table('up_friend')->where($where)->update([
                        'friend_status' => 1,
                        'friend_verify' => $friend_verify,
                        'friend_from' => $friend_from,
                        'friend_time' => date('Y-m-d H:i:s')
                    ]);
                }
            }else{
                $data1['friend_user_id'] = $user_id;
                $data1['friend_other_user'] = $userId;
                $data1['friend_ask_id'] = $user_id;
                $data1['friend_group'] = $groupid;
                $data1['friend_status'] = 1;
                $data1['friend_time'] = date('Y-m-d H:i:s',time());
                $data1['friend_remark'] = '';
                $data1['friend_verify'] = $friend_verify;
                $data1['friend_from'] = $friend_from;
                $res = Db::table('up_friend')->insert($data1);
            }
            if($res){
                $str = '您有新的添加好友申请';
                $list = [];
                $user_to_id = (string)$userId;
                array_push($list, $user_to_id);
                try{
                    $this->Jpush(1, $list, $str, ['send_type' => 9]);
                }catch(\Exception $e){

                }
                return  json(array('status'=>200,'msg'=>"成功"));
            }else{
                return  json(array('status'=>100,'msg'=>"失败"));
            }
        }else{
            return  json(array('status'=>100,'msg'=>"分组数据出错，请刷新重试"));
        }

    }

    /**
     * 联系人首页
     * @return \think\response\Json
     */
    public function friendList(){
        extract(input());
        $this->createGroupBefore($user_id);
        $count_ask = Db::table('up_friend')
            ->where('friend_other_user',$user_id)
            ->where('friend_status',1)
            ->count();
        $group = Db::table('up_friend_group')
            ->where('fg_user_id',$user_id)
            ->order('fg_time ASC')
            ->field('fg_id,fg_name')
            ->select();
        $data = array();
        if($group){
            foreach ($group as $k=>$v){
                $where = array();
                $where['friend_status'] = 2;
                $where['friend_user_id'] = $user_id;
                $where['friend_group'] = $v['fg_id'];
                $list = Db::table('up_friend')->alias('a')
                    ->join('up_u_user uuu','uuu.user_id = a.friend_other_user','left')
                    ->field('friend_other_user,friend_id,friend_remark,uuu.user_username,uuu.user_image')
                    ->order('a.friend_time desc')
                    ->where($where)
//                    ->page($page,20)
                    ->select();
                $data[$k]['name'] = $v['fg_name'];
                $data[$k]['all'] = $list;
//                $data[$v['fg_name']] = $list;
            }
        }
        return  json(array('status'=>200,'msg'=>$data,'ask_num'=>$count_ask));

    }
    /**
     * page
     * 新朋友申请列表：
     * @return \think\response\Json
     */
    public function askFriendList(){
        extract(input());
        $where = [
            'friend_other_user' => $user_id,
//            'friend_status' => ['in','1,3']
        ];
        $where2 = [
            'friend_other_user' => $user_id,
//            'friend_status' => 1,
            'friend_ask_id' => ['<>',$user_id]
        ];
        $data = Db::table('up_friend')->alias('a')
            ->join('up_u_user uuu','uuu.user_id = a.friend_user_id','left')
            // ->where(function ($query) use ($where){
                // $query->where($where);
            // })
            // ->whereOr(function ($query) use ($where2){
                // $query->where($where2);
            // })
			->where($where2)
            ->order('friend_status ASC')
            ->field('uuu.user_username,uuu.user_image,friend_user_id,friend_status,friend_verify,user_district_str,friend_from')
            ->page($page,20)
            ->select();
        return  json(array('status'=>200,'msg'=>$data));

    }

    /**
     * 同意好友  拒绝好友
     * @return \think\response\Json
     */
    public function agreeFriendOrNot(){
        $user_id = input('param.user_id');
        $groupid = $this->createGroupBefore($user_id);
        $other_id = input('param.other_id');
        $type = input('param.type');//2同意  3拒绝
        $where['friend_user_id'] = $other_id;
        $where['friend_other_user'] = $user_id;
        //查询数据
        $info = Db::table('up_friend')->where($where)->find();
        if($info['friend_status'] != 1){
            return  json(array('status'=>100,'msg'=>"已经操作过了"));
        }else{
            if($type == 2){//同意
                Db::startTrans();
                try{
                    $where2['friend_user_id'] = $user_id;
                    $where2['friend_other_user'] =  $other_id;
                    //
                    $res = Db::table('up_friend')->where($where2)->find();
                    if($res['friend_id']!=''){//证明已经存在数据了
                        $data1['friend_status'] = 2;
                        $data1['friend_time'] = date('Y-m-d H:i:s',time());
                        Db::table('up_friend')->where($where)->update($data1);
                        Db::table('up_friend')->where($where2)->update($data1);
                    }else{//没有数据
                        $data2['friend_user_id'] = $user_id;
                        $data2['friend_other_user'] = $other_id;
                        $data2['friend_ask_id'] = $other_id;
                        $data2['friend_group'] = $groupid;
                        $data2['friend_status'] = 2;
                        $data2['friend_time'] = date('Y-m-d H:i:s');
                        $data2['friend_remark'] = '';
                        $data2['friend_verify'] = '';
                        Db::table('up_friend')->where($where)->setField('friend_status',2);
                        Db::table('up_friend')->insertGetId($data2);
                    }
                    Db::commit();
                    return  json(array('status'=>200,'msg'=>"成功"));
                }catch (\Exception $e) {
                    Db::rollback();
                    return  json(array('status'=>100,'msg'=>"失败"));
                }
            }elseif ($type==3){//拒绝
                $res1 = Db::table('up_friend')->where($where)->setField('friend_status',3);
                if($res1){
                    return  json(array('status'=>200,'msg'=>"成功"));
                }else{
                    return  json(array('status'=>100,'msg'=>"失败"));
                }
            }else{
                return  json(array('status'=>100,'msg'=>"参数有误"));
            }
        }

    }

    /**
     * other_id remark
     * 备注好友
     * @return \think\response\Json
     */
    public function remarkFriend(){
        $user_id = input('param.user_id');
        $other_id = input('param.other_id');
        $remark = input('param.remark');
        $where2['friend_user_id'] = $user_id;
        $where2['friend_other_user'] =  $other_id;
        $res = Db::table('up_friend')->where($where2)->update([
            'friend_remark' => $remark
        ]);
        if($res){
            return  json(array('status'=>200,'msg'=>"成功"));
        }else{
            return  json(array('status'=>100,'msg'=>"失败"));
        }
    }
    /**
     * other_id
     * 分组管理好友——1
     * @return \think\response\Json
     */
    public function groupFriend(){
        $user_id = input('param.user_id');
        $other_id = input('param.other_id');

        $where2['friend_user_id'] = $user_id;
        $where2['friend_other_user'] =  $other_id;
        $nowgid = Db::table('up_friend')->where($where2)->value('friend_group');
        $groups = Db::table('up_friend_group')->where('fg_user_id',$user_id)->select();
        return  json(array('status'=>200,'msg'=>$groups,'nowgid'=>$nowgid));
    }
    /**
     * other_id $fg_id
     * 分组管理好友——2
     * @return \think\response\Json
     */
    public function groupFriendEdit(){
        $user_id = input('param.user_id');
        $other_id = input('param.other_id');
        $fg_id = input('param.fg_id');
        $where2['friend_user_id'] = $user_id;
        $where2['friend_other_user'] =  $other_id;
        $res = Db::table('up_friend')->where($where2)->update([
            'friend_group' => $fg_id
        ]);
        if($res){
            return  json(array('status'=>200,'msg'=>"成功"));
        }else{
            return  json(array('status'=>100,'msg'=>"失败"));
        }
    }
    /**
     * other_id
     * 删除好友
     * @return \think\response\Json
     */
    public function delFriend(){
        $user_id = input('param.user_id');
        $other_id = input('param.other_id');
        $where['friend_user_id'] = $other_id;
        $where['friend_other_user'] = $user_id;
        $where2['friend_user_id'] = $user_id;
        $where2['friend_other_user'] =  $other_id;
        Db::startTrans();
        try{
            Db::table('up_friend')->where($where)->delete();
            Db::table('up_friend')->where($where2)->delete();
            Db::commit();
            return  json(array('status'=>200,'msg'=>"成功"));
        }catch (\Exception $e) {
            Db::rollback();
            return  json(array('status'=>100,'msg'=>"失败"));
        }
    }

    /**
     * 分组管理
     * @return \think\response\Json
     */
    public function myGroups(){
        $user_id = input('param.user_id');
        $groupid = $this->createGroupBefore($user_id);
        $groups = Db::table('up_friend_group')->where('fg_user_id',$user_id)->select();
        return  json(array('status'=>200,'msg'=>$groups));
    }
    /**
     * 分组管理——添加
     * @return \think\response\Json
     */
    public function myGroupAdd(){
        $user_id = input('param.user_id');
        $groupid = $this->createGroupBefore($user_id);
        if($groupid != false){
            $fg_name = input('param.fg_name');
            if($fg_name == '默认分组'){
                return  json(array('status'=>100,'msg'=>"不能起此名字"));
            }
            $have = Db::table('up_friend_group')
                ->where('fg_user_id',$user_id)
                ->where('fg_name',$fg_name)
                ->find();
            if($have){
                return  json(array('status'=>100,'msg'=>"名字重复"));
            }else{
                $res = Db::table('up_friend_group')->insert([
                    'fg_user_id' => $user_id,
                    'fg_name' => $fg_name,
                    'fg_time' => date('Y-m-d H:i:s')
                ]);
                if($res){
                    return  json(array('status'=>200,'msg'=>"成功"));
                }else{
                    return  json(array('status'=>100,'msg'=>"失败"));
                }
            }
        }else{
            return  json(array('status'=>100,'msg'=>'分组数据错误，请刷新重试'));
        }

    }
    /**
     * 分组管理——删除
     * @return \think\response\Json
     */
    public function myGroupDel(){
        $fg_id = input('param.fg_id');
        $user_id = input('param.user_id');
        $groupid = $this->createGroupBefore($user_id);
        if($groupid != false){
            if($groupid == $fg_id){
                return  json(array('status'=>100,'msg'=>"默认分组不能删除"));
            }
            Db::startTrans();
            try{
                Db::table('up_friend_group')
                    ->where('fg_id',$fg_id)
                    ->delete();
                Db::table('up_friend')
                    ->where('friend_user_id',$user_id)
                    ->where('friend_group',$fg_id)
                    ->setField('friend_group',$groupid);
                Db::commit();
                return  json(array('status'=>200,'msg'=>"成功"));
            }catch (\Exception $e) {
                Db::rollback();
                return  json(array('status'=>100,'msg'=>"失败"));
            }
        }else{
            return  json(array('status'=>100,'msg'=>'分组数据错误，请刷新重试'));
        }

    }

    /**
     * $keyword
     * page（传page和limit是因为查看更多功能）
     * limit
     * 列表处只展示多5个，更多进去再展示（创建群聊选择好友时也用这个）
     * 搜索好友（和群聊分开是因为查看更多功能）
     * @return \think\response\Json
     */
    public function selectFriends(){
        extract(input());
        $list = array();
        $keyword = input('param.keyword');
        $where = array();
        $where['friend_user_id'] = $user_id;
        $where['friend_status'] = 2;
        if($keyword!=''){
            $where['user_username|user_phone'] = array('like','%'.$keyword.'%');
        }
//        else{
//            return  json(array('status'=>200,'msg'=>$list));
//        }
        $list = Db::table('up_friend')->alias('f')
            ->join('up_u_user u','f.friend_other_user = u.user_id','LEFT')
            ->where($where)
            ->field('friend_other_user,user_username,user_image')
            ->page($page,$limit)
            ->select();
        return  json(array('status'=>200,'msg'=>$list));
    }
    /**
     * $keyword
     * page
     * limit
     * 列表处只展示多5个，更多进去再展示
     * 搜索群聊
     * @return \think\response\Json
     */
    public function selectGroups(){
        extract(input());
        $list = array();
        $where = array();
        $where['g_uids'] = array('like','%,'.$user_id.',%');
        $where['g_status'] = 1;
        if($keyword!=''){
            $where['g_name'] = array('like','%'.$keyword.'%');
        }else{
            return  json(array('status'=>200,'msg'=>$list));
        }
        $list = Db::table('up_group')
            ->where($where)
            ->field('g_name,g_id,g_thumb')
            ->page($page,$limit)
            ->select();
        return  json(array('status'=>200,'msg'=>$list));
    }
    /**
     * $keyword page
     * 添加新的好友
     * @return \think\response\Json
     */
    public function selectUsers(){
        extract(input());
        $list = array();
        $keyword = input('param.keyword');
        $where = array();
        $where2 = array();
        if($keyword!=''){
            $where['user_username'] = array('like','%'.$keyword.'%');
            $where['user_id'] = array('<>',$user_id);
            $where['user_status'] = 1;
            $where2['user_phone'] = $keyword;
            $where2['user_status'] = 1;
            $where2['user_id'] = array('<>',$user_id);
        }else{
            return  json(array('status'=>200,'msg'=>$list));
        }
        $list = Db::table('up_u_user')
            ->where(function ($query) use ($where){
                $query->where($where);
            })
            ->whereOr(function ($query) use ($where2){
                $query->where($where2);
            })
            ->field('user_id,user_username,user_image')
            ->page($page,20)
            ->select();
        if($list){
            foreach ($list as $key=>&$vo){
                $map['friend_user_id'] = $user_id;
                $map['friend_other_user'] = $vo['user_id'];
                //查询本人是否已经添加搜索的这个好友了
                $info = Db::table('up_friend')->where($map)->find();
                if(empty($info)){//没有添加这个人好友
                    $vo['status'] = 0;//添加好友
                }else{
                    if($info['friend_status']==2){//已经是好友
                        $vo['status'] = 2;
                    }else{
                        $vo['status'] = 1;//还不是好友
                    }
                }
            }
        }

        return  json(array('status'=>200,'msg'=>$list));
    }
    /**
     * 给老汤的，聊天用：根据id返回信息
     */
    public function byIdsGetInfos()
    {
        $uids = trim($_POST['uids'],',');
        Db::table('up_zz_error')->insert(['error'=>$uids,'type'=>1]);
        $pd = Db::table('up_u_user')
            ->where('user_id','in',$uids)
            ->field('user_username,user_id,user_image')
            ->select();
        if($pd){
            foreach ($pd as $k=>$v){
                $pd[$k]['friend_remark'] = Db::table('up_friend')
                    ->where('friend_user_id',$_POST['user_id'])
                    ->where('friend_other_user',$v['user_id'])
                    ->value('friend_remark');
            }
        }
        return json_encode(['status'=>200,'msg'=>$pd]);
    }
    /**
     * 给老汤的，聊天用：这个id是不是我的好友
     */
    public function isMyFriend()
    {
        extract(input());
        $one = Db::table('up_friend')
            ->where('friend_user_id',$user_id)
            ->where('friend_other_user',$uid)
            ->find();
        $status = 0;
        if($one && $one['friend_status'] == 2){
            $status = 1;
        }
        return json_encode(['status'=>200,'msg'=>$status]);
    }

}